<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请部门" prop="department">
        <el-select v-model="queryParams.department" placeholder="请选择申请部门" clearable filterable>
          <el-option v-for="dict in departmentOptions" :key="dict.deptId" :label="dict.deptName" :value="dict.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="partyId">
        <el-select v-model="queryParams.partyId" placeholder="请选择申请人" clearable filterable>
          <el-option v-for="dict in partyIdOptions" :key="dict.partyId" :label="dict.firstName" :value="dict.partyId" />
        </el-select>
      </el-form-item>
      <el-form-item label="开票日期">
        <el-date-picker v-model="daterangeInvoiceDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="审批状态" prop="flowStatus">
        <el-select v-model="queryParams.flowStatus" placeholder="请选择审批状态" clearable>
          <el-option v-for="dict in flowStatusOptions" :key="dict.enumCode" :label="dict.description"
            :value="dict.enumCode" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini">
          <router-link :to="'/workflow/approve/invoice_application/apply'" class="link-type">
            <span>开票申请</span>
          </router-link>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['ehr:invoice_application:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="invoice_applicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请编号" align="center" prop="applyId" />
      <el-table-column label="申请部门" align="center" prop="department" width="100" :formatter="departmentFormat" />
      <el-table-column label="申请人" align="center" prop="partyId" width="100" :formatter="partyIdFormat" />
      <el-table-column label="开票事由" align="center" prop="reason" width="120" />
      <el-table-column label="开票日期" align="center" prop="invoiceDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.invoiceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发票类型" align="center" prop="invoiceType" width="100" :formatter="invoiceTypeFormat" />
      <el-table-column label="开票金额" align="right" prop="invoiceAmount" :formatter="numberFormat"/>
      <el-table-column label="审批状态" align="center" prop="flowStatus" width="100" :formatter="flowStatusFormat" />
      <el-table-column label="更新时间" align="center" prop="lastUpdatedStamp" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastUpdatedStamp, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleDetail(scope.row)"
            v-hasPermi="['ehr:invoice_application:detail']">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改开票申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-bind:disabled=detailFlag>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请部门" prop="department">
              <span>{{ departmentFormat(form) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人" prop="partyId">
              <span>{{ personFormat(form) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开票事由" prop="reason">
              <span>{{ form.reason }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开票日期" prop="invoiceDate">
              <span>{{ form.invoiceDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <span>{{ invoiceTypeFormat(form) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="应税项目" prop="taxableItems">
              <span>{{ form.taxableItems }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="税率" prop="taxRate">
              <span>{{ formatNumber(form.taxRate) }}%</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票金额" prop="invoiceAmount">
              <span>{{ formatNumber(form.invoiceAmount) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <span>{{ form.companyName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纳税人识别号" prop="taxpayerId">
              <span>{{ form.taxpayerId }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="地址电话" prop="addressAndPhone">
              <span>{{ form.addressAndPhone }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户行及账号" prop="bankAndAccount">
              <span>{{ form.bankAndAccount }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <span>{{ form.remark }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="附件" prop="affixFilePath">
              <image-upload v-model="form.affixFilePath" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批状态" prop="flowStatus">
              <span>{{ flowStatusFormat(form) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批人" prop="approver">
              <span>{{ approverFormat(form) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="editFlag" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInvoice_application, getInvoice_application, delInvoice_application, addInvoice_application, updateInvoice_application } from "@/api/ehr/invoice_application";
// person enum api
import { getPersonEnum } from "@/api/ehr/person";
export default {
  name: "Invoice_application",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 开票申请表格数据
      invoice_applicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 人员字典
      personOptions: [],
      // 申请部门业务字典
      departmentOptions: [],
      // 申请人业务字典
      partyIdOptions: [],
      // 审批人时间范围
      daterangeInvoiceDate: [],
      // 发票类型业务字典
      invoiceTypeOptions: [],
      // 审批状态业务字典
      flowStatusOptions: [],
      // 操作标识,用于区分是新增还是修改
      updateFlag: false,
      // 操作标识,用于区分是详情
      detailFlag: false,
      // 操作标识,用于区分编辑状态
      editFlag: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "", // 排序字段
        isAsc: "", // 升序或降序 大写的 ASC或DESC,为空代表升序
        department: null,
        partyId: null,
        invoiceDate: null,
        flowStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        department: [
          { required: true, message: "申请部门不能为空", trigger: "change" }
        ],
        partyId: [
          { required: true, message: "申请人不能为空", trigger: "change" }
        ],
        reason: [
          { required: true, message: "开票事由不能为空", trigger: "blur" }
        ],
        invoiceDate: [
          { required: true, message: "开票日期不能为空", trigger: "blur" }
        ],
        invoiceType: [
          { required: true, message: "发票类型不能为空", trigger: "change" }
        ],
        taxableItems: [
          { required: true, message: "应税项目不能为空", trigger: "blur" }
        ],
        taxRate: [
          { required: true, message: "税率不能为空", trigger: "blur" }
        ],
        invoiceAmount: [
          { required: true, message: "开票金额不能为空", trigger: "blur" }
        ],
        companyName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        taxpayerId: [
          { required: true, message: "纳税人识别号不能为空", trigger: "blur" }
        ],
        addressAndPhone: [
          { required: true, message: "地址电话不能为空", trigger: "blur" }
        ],
        bankAndAccount: [
          { required: true, message: "开户行及账号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    // 人员字典
    getPersonEnum().then((response) => {
      this.personOptions = response.data;
    });
    // 申请部门业务字典
    this.getEntityDicts("SysDept:deptId:deptName").then((response) => {
      this.departmentOptions = response.data;
    });
    // 申请人业务字典
    this.getEntityDicts("person:partyId:firstName").then((response) => {
      this.partyIdOptions = response.data;
    });
    // 发票类型业务字典
    this.getEnumDicts("INVOICE_TYPE").then((response) => {
      this.invoiceTypeOptions = response.data;
    });
    // 审批状态业务字典
    this.getEnumDicts("FLOW_STATUS").then((response) => {
      this.flowStatusOptions = response.data;
    });
    this.getList();
  },
  methods: {
    formatNumber(value) {
      if (value !== null) {
        return parseFloat(value).toFixed(2);
      }
    },
    numberFormat(row, column) {
      if (row.invoiceAmount !== null) {
        return parseFloat(row.invoiceAmount).toFixed(2);
      }
    },
    // 人员字典转换
    personFormat(row, column) {
      let val = null;
      this.personOptions.forEach((item, index) => {
        if (row.partyId === item.partyId) {
          val = item.name;
        }
      });
      return val;
    },
    // 审批人字典转换
    approverFormat(row, column) {
      let val = null;
      this.personOptions.forEach((item, index) => {
        if (row.approver === item.userId + "") {
          val = item.firstName;
        }
      });
      return val;
    },
    departmentFormat(row, column) {
      let val = null;
      this.departmentOptions.forEach((item, index) => {
        if (row.department === item.deptId + "") {
          val = item.deptName;
        }
      });
      return val;
    },
    partyIdFormat(row, column) {
      let val = null;
      this.partyIdOptions.forEach((item, index) => {
        if (row.partyId === item.partyId) {
          val = item.firstName;
        }
      });
      return val;
    },
    invoiceTypeFormat(row, column) {
      let val = null;
      this.invoiceTypeOptions.forEach((item, index) => {
        if (row.invoiceType === item.enumCode) {
          val = item.description;
        }
      });
      return val;
    },
    flowStatusFormat(row, column) {
      let val = null;
      this.flowStatusOptions.forEach((item, index) => {
        if (row.flowStatus === item.enumCode) {
          val = item.description;
        }
      });
      return val;
    },
    /** 查询开票申请列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeInvoiceDate && '' != this.daterangeInvoiceDate) {
        this.queryParams.params["beginInvoiceDate"] = this.daterangeInvoiceDate[0];
        this.queryParams.params["endInvoiceDate"] = this.daterangeInvoiceDate[1];
      }
      listInvoice_application(this.queryParams).then(response => {
        this.invoice_applicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        applyId: null,
        department: null,
        partyId: null,
        reason: null,
        invoiceDate: null,
        invoiceType: null,
        taxableItems: null,
        taxRate: null,
        invoiceAmount: null,
        companyName: null,
        taxpayerId: null,
        addressAndPhone: null,
        bankAndAccount: null,
        remark: null,
        affixFilePath: null,
        statusId: null,
        flowInstId: null,
        flowStatus: "0",
        approver: null,
        lastUpdatedStamp: null,
        lastUpdatedTxStamp: null,
        createdStamp: null,
        createdTxStamp: null,
        orgId: null,
        deptId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeInvoiceDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editFlag = true,
        this.updateFlag = false;
      this.detailFlag = false;
      this.reset();
      this.open = true;
      this.title = "添加开票申请";
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.editFlag = false,
        this.updateFlag = false;
      this.detailFlag = true;
      this.reset();
      const applyId = row.applyId || this.ids
      getInvoice_application(applyId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "开票申请详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editFlag = true;
      this.updateFlag = true;
      this.detailFlag = false;
      this.reset();
      const applyId = row.applyId || this.ids
      getInvoice_application(applyId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改开票申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.applyId != null && this.updateFlag) {
            updateInvoice_application(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInvoice_application(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const applyIds = row.applyId || this.ids;
      this.$modal.confirm('是否确认删除开票申请编号为"' + applyIds + '"的数据项？').then(function () {
        return delInvoice_application(applyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ehr/invoice_application/export', {
        ...this.queryParams
      }, `invoice_application_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
